package com.xincheng.shuimalong.activity.recept;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.xincheng.library.util.ClipBoardUtil;
import com.xincheng.library.util.CommonUtil;
import com.xincheng.library.util.PrefUtil;
import com.xincheng.library.util.UIUtil;
import com.xincheng.library.widget.StateButton;
import com.xincheng.library.widget.alertview.AlertView;
import com.xincheng.library.widget.alertview.OnAlertItemClickListener;
import com.xincheng.library.xlog.LogUtils;
import com.xincheng.library.xlog.XLog;
import com.xincheng.shuimalong.R;
import com.xincheng.shuimalong.activity.BaseActivity;
import com.xincheng.shuimalong.activity.EvaluateActivity;
import com.xincheng.shuimalong.activity.OrderDetailActivity;
import com.xincheng.shuimalong.activity.sell.LookGuaranteeActivity;
import com.xincheng.shuimalong.api.AppUrl;
import com.xincheng.shuimalong.api.BaseObserver;
import com.xincheng.shuimalong.api.GetParam;
import com.xincheng.shuimalong.api.PostParam;
import com.xincheng.shuimalong.api.RetroSubscrube;
import com.xincheng.shuimalong.common.Constant;
import com.xincheng.shuimalong.common.IntentKey;
import com.xincheng.shuimalong.common.OrderConfig;
import com.xincheng.shuimalong.common.PrefKey;
import com.xincheng.shuimalong.common.RequestCodeKey;
import com.xincheng.shuimalong.entity.Order;
import com.xincheng.shuimalong.entity.OrderDetail;
import com.xincheng.shuimalong.entity.config.CompanyLogo;
import com.xincheng.shuimalong.manager.GlideOptionsManager;
import com.xincheng.shuimalong.manager.OrderExitManager;
import com.xincheng.shuimalong.util.BitmapUtil;
import com.xincheng.shuimalong.util.ConfigUtil;
import com.xincheng.shuimalong.util.GsonUtil;
import com.xincheng.shuimalong.util.ShowActivity;

import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by xiaote on 2017/7/5.
 * 收单方待回单
 */

public class ReceiptBackActivity extends BaseActivity {
    @BindView(R.id.order_detail_filestaus_tv)
    TextView mFileStatusTv;
    @BindView(R.id.order_detail_status_tv)
    TextView mStatusTv;
    @BindView(R.id.order_detail_orderno_tv)
    TextView mOrderNoTv;
    @BindView(R.id.order_detail_updatetime_tv)
    TextView mUpdateTimeTv;
    @BindView(R.id.receipt_pay_money_tv)
    TextView mPayMoneyTv;
    @BindView(R.id.receipt_pay_date_tv)
    TextView mPayDateTv;
    @BindView(R.id.receipt_vci_guarantee_tv)
    TextView mVciGuaranteeTv;
    @BindView(R.id.receipt_tci_guarantee_tv)
    TextView mTciGuaranteeTv;
    @BindView(R.id.receipt_issue_type_tv)
    TextView mIssueTypeTv;
    @BindView(R.id.receipt_back_type_tv)
    TextView mReceiptTypeTv;
    @BindView(R.id.bottom_layout)
    LinearLayout mBottomLayout;
    @BindView(R.id.evaluate_btn)
    StateButton mEvaluateBtn;
    @BindView(R.id.sign_for_submit_btn)
    StateButton mSignForBtn;
    @BindView(R.id.receipt_back_submit_btn)
    StateButton mReceiptBackBtn;
    @BindView(R.id.receipt_back_type_layout)
    LinearLayout mBackTypeLayout;
    @BindView(R.id.vci_guarantee_look_tv)
    TextView mVciGuaranteeLookTv;
    @BindView(R.id.tci_guarantee_look_tv)
    TextView mTciGuaranteeLookTv;
    //名称 头像 手机号码 保险logo
    @BindView(R.id.iv_avatar)
    ImageView ivAvatar;
    @BindView(R.id.tv_order_name)
    TextView tvOrderName;
    @BindView(R.id.tv_order_phone)
    TextView tvOrderPhone;
    @BindView(R.id.iv_insurance_img)
    ImageView ivInsuranceImg;
    private String mToken;
    private int mBidId;
    private int mOrderStatus;
    private int mOrderConfig;
    private OrderDetail mOrderDetail;
    private long mCreateTime;
    private int mFileStatus;

    @Override
    public int getLayoutResId() {
        return R.layout.activity_receipt_back;
    }

    @Override
    public void initData() {
        initTitleBar(getString(R.string.order_detail1));
        OrderExitManager.getInstance().addActivity(this);
        mToken = PrefUtil.getString(this, PrefKey.TOKEN, "");
        Bundle extras = getIntent().getExtras();
        mBidId = extras.getInt(IntentKey.BID_ID);
        mOrderConfig = extras.getInt(IntentKey.ORDER_CONFIG);
        mOrderStatus = extras.getInt(IntentKey.ORDER_STATUS);
        mCreateTime = extras.getLong(IntentKey.CREATE_TIME);
        mFileStatus = extras.getInt(IntentKey.FILE_STATUS, 0);
        tvOrderName.setText(extras.getString(IntentKey.NICK_NAME));
        tvOrderPhone.setText(extras.getString(IntentKey.MOBILE));
        Glide.with(getContext()).load(extras.getString(IntentKey.AVATAR)).apply(GlideOptionsManager.getInstance()
                .getRequestOptions()).into(ivAvatar);

        mOrderNoTv.setText(getString(R.string.order_no, ""));
        switch (mOrderConfig) {
            case OrderConfig.RECEIPT:
                switch (mOrderStatus) {
                    case 3:
                        mReceiptBackBtn.setVisibility(View.VISIBLE);
                        if (mFileStatus == 1) {
                            mStatusTv.setText("待签收");
                            mReceiptBackBtn.setEnabled(false);
                        } else if(mFileStatus == 2){
                            mStatusTv.setText("待回单");
                            mReceiptBackBtn.setEnabled(false);
                        } else if(mFileStatus == 3) {
                            mStatusTv.setText("待签收");
                            mReceiptBackBtn.setEnabled(true);
                        }
                        break;
                    case 4:
                        mStatusTv.setText("待评价");
                        mEvaluateBtn.setVisibility(View.VISIBLE);
                        break;
                }
                break;
            case OrderConfig.SELL:
                switch (mOrderStatus) {
                    case 2:
                        mBackTypeLayout.setVisibility(View.GONE);
                        mSignForBtn.setVisibility(View.VISIBLE);
                        if(mFileStatus == 0) {
                            mStatusTv.setText("待出单");
                            mSignForBtn.setEnabled(false);
                        } else {
                            mStatusTv.setText("待签收");
                            mSignForBtn.setEnabled(true);
                        }
                        break;
                    case 3:
                        mFileStatusTv.setVisibility(View.VISIBLE);
                        mFileStatusTv.setText("回单寄出");
                        mStatusTv.setText("待签收");
                        break;
                    case 4:
                        mStatusTv.setText("待评价");
                        mEvaluateBtn.setVisibility(View.VISIBLE);
                        break;
                }
                break;
        }
        getOrderDetail();
    }

    private void getOrderDetail() {
        switch (mOrderConfig) {
            case OrderConfig.RECEIPT:
                RetroSubscrube.getInstance().getSubscrube(GetParam.viewAcOrder(mToken, mBidId),
                        new BaseObserver(this, getString(R.string.loading_data)) {
                            @Override
                            protected void onHandleSuccess(Object data, String msg) {
                                if (data != null) {
                                    mOrderDetail = GsonUtil.parseData(data, OrderDetail.class);
                                    parseDetail();
                                }
                            }
                        });
                break;
            case OrderConfig.SELL:
                RetroSubscrube.getInstance().getSubscrube(GetParam.viewBillOrder(mToken, mBidId),
                        new BaseObserver(this, getString(R.string.loading_data)) {
                            @Override
                            protected void onHandleSuccess(Object data, String msg) {
                                if (data != null) {
                                    mOrderDetail = GsonUtil.parseData(data, OrderDetail.class);
                                    parseDetail();
                                }
                            }
                        });
                break;
        }

    }

    private void parseDetail() {
        mOrderNoTv.setText(getString(R.string.order_no, mOrderDetail.getOrderNo()));
        mUpdateTimeTv.setText(mOrderDetail.getUpdateTime());
        mPayMoneyTv.setText(getString(R.string.money_value, mOrderDetail.getTotalMoney()));
        mPayDateTv.setText(mOrderDetail.getPayTime());
        mIssueTypeTv.setText(mOrderDetail.getShippingMsg());
        mVciGuaranteeTv.setText(mOrderDetail.getVciNo());
        mTciGuaranteeTv.setText(mOrderDetail.getTciNo());
        mReceiptTypeTv.setText(mOrderDetail.getrShippingMsg());
        if (!CommonUtil.isEmpty(mOrderDetail.getVciCt())) {
            mVciGuaranteeLookTv.setVisibility(View.VISIBLE);
        }
        if (!CommonUtil.isEmpty(mOrderDetail.getTciCt())) {
            mTciGuaranteeLookTv.setVisibility(View.VISIBLE);
        }
        CompanyLogo companyLogo = ConfigUtil.getCompanyLogoById(this,mOrderDetail.getCompanyId());
        final int screenWith = UIUtil.getDisplaySize(this)[0];
        if (companyLogo != null) {
            Glide.with(this).asBitmap().load(companyLogo.getLogo()).into(new SimpleTarget<Bitmap>() {
                @Override
                public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
                    Bitmap bitmap = BitmapUtil.zoomImg(resource, screenWith / 3);
                    ivInsuranceImg.setImageBitmap(bitmap);
                }
            });
        }
        if (companyLogo != null) {
            Glide.with(this).asBitmap().load(companyLogo.getLogo()).into(new SimpleTarget<Bitmap>() {
                @Override
                public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
                    Bitmap bitmap = BitmapUtil.zoomImg(resource, screenWith / 3);
                    ivInsuranceImg.setImageBitmap(bitmap);
                }
            });
        }
    }

    @OnClick({R.id.receipt_orderdetail_tv, R.id.receipt_back_submit_btn, R.id.evaluate_btn, R.id.sign_for_submit_btn,
            R.id.vci_guarantee_look_tv, R.id.tci_guarantee_look_tv,R.id.tv_order_phone})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.receipt_orderdetail_tv://查看订单详情
                if (mOrderDetail != null) {
                    Bundle extras = new Bundle();
                    extras.putInt(IntentKey.FROM, 1);
                    extras.putParcelable(IntentKey.ORDER_DETAIL, mOrderDetail);
                    extras.putLong(IntentKey.CREATE_TIME, mCreateTime);
                    ShowActivity.showActivity(this, OrderDetailActivity.class, extras);
                }
                break;
            case R.id.evaluate_btn://评价
                Bundle extras = new Bundle();
                extras.putInt(IntentKey.BID_ID, mBidId);
                extras.putInt(IntentKey.ORDER_CONFIG, mOrderConfig);
                ShowActivity.showActivityForResult(this, EvaluateActivity.class, extras,
                        RequestCodeKey.EVALUATE);
                break;
            case R.id.receipt_back_submit_btn://回单签收
            case R.id.sign_for_submit_btn://确认签收
                showAlertView();
                break;
            case R.id.vci_guarantee_look_tv://查看商业险保单
                extras = new Bundle();
                extras.putString(IntentKey.GUARANTEE_IMAGE, mOrderDetail.getVciCt());
                ShowActivity.showActivity(this, LookGuaranteeActivity.class, extras);
                break;
            case R.id.tci_guarantee_look_tv://查看交强险保单

                extras = new Bundle();
                extras.putString(IntentKey.GUARANTEE_IMAGE, mOrderDetail.getTciCt());
                ShowActivity.showActivity(this, LookGuaranteeActivity.class, extras);
                break;
            case R.id.tv_order_phone:
                if (CommonUtil.isEmpty(tvOrderPhone)) {
                    showToast("抱歉，没有联系方式");
                    return;
                }
                String mobile_phone = tvOrderPhone.getText().toString().trim();
                showCallAlert(mobile_phone);
                break;
        }
    }
    private void showCallAlert(final String mobile) {
        new AlertView(this, null, null, getString(R.string.cancel), null, Constant.CALL_WAY,
                AlertView.Style.ActionSheet, new OnAlertItemClickListener() {
            @Override
            public void onItemClick(AlertView alertView, int position) {
                switch (position) {
                    case 0: //呼叫
                        ShowActivity.callPhone(getContext(), mobile);
                        break;
                    case 1: //复制号码
                        ClipBoardUtil.copyText(getContext(), mobile);
                        break;
                    case 2: //添加到通讯录
                        ShowActivity.addContact(getContext(), mobile);
                        break;
                }
            }
        }).show();
    }
    @Override
    public void addListener() {

    }

    private void showAlertView() {
        //0-未出单 1-已出单待签收 2-已签收待回单 3已回单待确认 4确认收到回单
//        switch (mOrderConfig) {
//            case OrderConfig.RECEIPT:
//                if (mFileStatus == 1) {
//                    CommonUtil.showToast(this, "请等待卖单方签收");
//                    return;
//                }
//                if (mFileStatus == 2) {
//                    CommonUtil.showToast(this, "请等待卖单方回单");
//                    return;
//                }
//                break;
//            case OrderConfig.SELL:
//                if (mFileStatus == 0) {
//                    CommonUtil.showToast(this, "请等待收单方出单");
//                    return;
//                }
//                break;
//        }
        String title = "";
        switch (mOrderConfig) {
            case OrderConfig.SELL:
                title = "请确认保单已签收？";
                break;
            case OrderConfig.RECEIPT:
                title = "请确认回单已签收？";
                break;
        }
        new AlertView(getContext(), null, title, getString(R.string.cancel),
                new String[]{getString(R.string.confirm)}, null, AlertView.Style.Alert,
                new OnAlertItemClickListener() {
                    @Override
                    public void onItemClick(AlertView alertView, int position) {
                        switch (position) {
                            case 0:
                                confirmFile();
                                break;
                        }
                    }
                }).show();
    }

    private void confirmFile() {
        BaseObserver observer = new BaseObserver(getContext(), getString(R.string.loading_submit)) {
            @Override
            protected void onHandleSuccess(Object data, String msg) {
                showToast("提交成功");
                Intent intent = new Intent();
                intent.putExtra(IntentKey.SIGN_RECEIVE_SUCCESS, true);
                setResult(RESULT_OK, intent);
                finish();

            }
        };
        Map<String, String> paramsMap = null;
        switch (mOrderConfig) {
            case OrderConfig.SELL:
                paramsMap = PostParam.fileConfirm(mToken, mBidId, 2);
                break;
            case OrderConfig.RECEIPT:
                paramsMap = PostParam.fileConfirm(mToken, mBidId, 4);
                break;
        }
        XLog.e("paramsMap=>" +paramsMap);
        if (!CommonUtil.isEmpty(paramsMap)) {
            RetroSubscrube.getInstance().postSubscrube(AppUrl.FILE_CONFIRM, paramsMap, observer);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case RequestCodeKey.EVALUATE:
                    Intent intent = new Intent();
                    intent.putExtra(IntentKey.EVALUATE,true);
                    setResult(RESULT_OK, intent);
                    finish();
                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
